package top.meeting.room.module.system.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.SqlPara;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.meeting.room.common.base.BaseRender;
import top.meeting.room.common.config.MainConfig;
import top.meeting.room.common.constant.ResultEnum;
import top.meeting.room.common.exceptions.HandlerException;
import top.meeting.room.common.kit.WxKit;
import top.meeting.room.module.book.model.Book;
import top.meeting.room.module.system.form.RegisterForm;
import top.meeting.room.module.system.form.UserInfoForm;
import top.meeting.room.module.system.model.Role;
import top.meeting.room.module.system.model.User;

/**
 * Created by Lyt on 2017/9/13.
 */

public class WxLoginService {

    private static final Logger _log = LoggerFactory.getLogger(WxLoginService.class);

    public static final WxLoginService me = new WxLoginService();


    private WxLoginService() {
    }

    /**
     * 保存一个新的微信用户
     *
     * @param openId
     * @return
     */
    public User saveUser(String openId) {
        RegisterForm registerForm = new RegisterForm();
        registerForm.setUserName("wx" + openId);
        registerForm.setPassword(openId);
        registerForm.setOpenId(openId);
        registerForm.setWxUserId(-1L);
        User user = UserService.me.register(registerForm);
        UserService.me.login(user.getUserName(), user.getOpenId());
        return user;
    }


    /**
     * 使用微信Code进行登录
     *
     * @param code
     */
    public User wxLogin(String code) {

        // 尝试获取 access_token
        JSONObject accessTokenJson = WxKit.getAccessToken(MainConfig.APP_ID, MainConfig.APP_SECRET);
        if (accessTokenJson == null) {
            _log.error("Access token is not available");
            throw new HandlerException(ResultEnum.DATA_ERROR, "微信接入失败");
        }

        String accessToken = String.valueOf(accessTokenJson.get("access_token"));
        JSONObject userInfo = WxKit.getUserInfo(accessToken, code);
        if (userInfo == null) {
            _log.error("Get User info with code {} fail", code);
            throw new HandlerException(ResultEnum.DATA_ERROR, "微信用户信息获取失败");
        }

        if (userInfo.getString("errcode") != null && userInfo.getIntValue("errcode") > 0) {    // 出错了
            _log.error("Error when get wei xin user info：{}", userInfo.getString("errcode"));
            throw new HandlerException(ResultEnum.DATA_ERROR, "获取用户授权信息出错");
        }

        _log.debug("The wei xin userInfo is: {}", userInfo);
        String openId = "";
        if (userInfo.getString("openid") != null) { // 非企业成员授权
            openId = userInfo.getString("openid");
        } else if (userInfo.getString("UserId") != null) { // 企业成员授权
            openId = userInfo.getString("UserId");
        }

        if (StrKit.isBlank(openId)) {
            throw new HandlerException(ResultEnum.DATA_ERROR, "微信用户Open");
        }
        UserService.me.remove();
        User user = (User) UserService.me.login("wx" + openId, openId);
        // OpenID对应的微信用户不存在，保存一个新的
        if (user == null) {
            User retVal = this.saveUser(openId);
            if (StrKit.notBlank(userInfo.getString("user_ticket"))) {
                JSONObject userDetail = WxKit.getUserDetail(accessToken, userInfo.getString("user_ticket"));
                // TODO:创建用户
                if (userDetail != null) {
                    String deptStr = userDetail.getString("department");
                    Integer deptId = Integer.parseInt(deptStr.substring(1, deptStr.length() - 1));
                    String deptName = (String) DepartmentService.departments.get(deptId);
                    Role role = RoleService.me.findByRoleName(deptName);
                    if (role != null) {
                        retVal = UserService.me.updateUserInfo(UserInfoForm.builder()
                                .dept(deptName)
                                .mobile("18888888888")
                                .realName(userDetail.getString("name"))
                                .build(), retVal.getId(), role.getId(), retVal.getId());
                    }
                }
            }
            return retVal;
        }
        return user;
    }

}

